package logic

import (
	"context"
	"database/sql"
	"time"

	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/social"
	"gitee.com/gao-deguang/easy-chat/apps/social/socialmodels"
	"gitee.com/gao-deguang/easy-chat/apps/user/models"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"gitee.com/gao-deguang/easy-chat/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

var (
	ErrHasJoinedGroup = xerr.NewMsg("已经入群")
	ErrHasReqedGroup  = xerr.NewMsg("已经申请过,请勿重复申请")
	ErrGroupNotExists = xerr.NewMsg("此群不存在，请确认群号")
)

type GroupPutInLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGroupPutInLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GroupPutInLogic {
	return &GroupPutInLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GroupPutInLogic) GroupPutIn(in *social.GroupPutInReq) (*social.GroupPutInResp, error) {
	// todo: add your logic here and delete this line
	//群号不存在不能申请
	group, err := l.svcCtx.GroupsModel.FindOne(l.ctx, in.GroupId)
	if err != nil && err != models.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewDBErr(), "FindGroupErr: %v ,groupId:%v req:%v", err, in.GroupId, in)
	}
	if group == nil {
		return nil, ErrGroupNotExists
	}
	//已经入群不能再申请
	member, err := l.svcCtx.GroupMembersModel.FindByGroupIdAndReqId(l.ctx, in.GroupId, in.UserId)
	if err != nil && err != models.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewDBErr(), "FindGroupMemberErr: FindByGroupIdAndReqIdErr:%v ,groupId:%v userId:%v", err, in.GroupId, in.UserId)
	}
	if member != nil {
		return nil, ErrHasJoinedGroup
	}
	//已经申请过不能再申请
	GroupPutInreq, err := l.svcCtx.GroupRequestsModel.FindByGroupIdAndReqId(l.ctx, in.GroupId, in.UserId)
	if err != nil && err != models.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewDBErr(), "GroupPutInReq:%v,FindGroupPutinReqErr: FindByGroupIdAndReqIdErr:%v ,groupId:%v userId:%v", GroupPutInreq, err, in.GroupId, in.UserId)
	}
	if GroupPutInreq != nil {
		return nil, ErrHasReqedGroup
	}

	//创建申请记录并加入数据库

	_, err = l.svcCtx.GroupRequestsModel.Insert(l.ctx, &socialmodels.GroupRequests{
		GroupId: in.GroupId,
		ReqId:   in.UserId,
		ReqMsg: sql.NullString{
			String: in.ReqMsg,
			Valid:  true,
		},
		ReqTime: time.Now(),
		JoinSource: sql.NullInt64{
			Int64: int64(in.JoinSource),
			Valid: true,
		},
		InviterUid: sql.NullString{
			String: in.InviterUid,
			Valid:  true,
		},
		HandleResult: sql.NullInt64{
			Int64: constant.NoHandelResult,
			Valid: true,
		},
	})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "GroupPutIn Insert Err:%v req:%v", err, in)
	}
	return &social.GroupPutInResp{}, nil
}
